<?php
/**
 * Created by PhpStorm.
 * User: XuChengPeng
 * Date: 2016/7/8
 * Time: 14:15
 */
use app\assets\AppAsset;
use yii\helpers\Html;

AppAsset::register($this);

$base =  Yii::$app->request->baseUrl;
AppAsset::addCss($this, $base . "/css/ToPay.css");
$this->title = '支付';

$user_id=\Yii::$app->user->id;
$attrIds = $attrString;
$no_remind = $no_remind;
$addressId = $address['addressbook_id'];
$cartIds = $cart_idString;
?>

<div style="min-height: 90px;margin-top: 7px;padding-left: 15px;padding-right: 15px;">
    <ul class="commonUi" onclick="goToNewAddress()">
        <?php if($addressId){?>
        <li class="commonLi">收货人：
            <span id="tvName"><?= $address['fullname']?></span>
            <span id="tvNumber"><?= $address['mobile']?></span>
        </li>
        <li style="margin-top: 10px; font-size: 14px;color: #4A4A4A;" class="commonLi">收货地址：
            <span id="tvAddress"><?=$address['province'] .
                $address['city'] . $address['district'] .
                $address['address']?></span>
        </li>
        <?php }else{?>
            <li class="commonLi" style="line-height: 80px;">添加新地址</li>
        <?php }?>
    </ul>
    <div class="rightIconDiv">
        <img style="margin-left: 20px" src="<?= $base?>/images/ic_right.png">
    </div>

</div>

<div class="lineDiv"></div>

<div style="height: 45px;padding-left: 15px;padding-right: 15px">
    <div class="shopNameDiv">
        <img class="shopNameImg" src="<?= $base?>/images/home_icon.png"/>
        <span id="tvShopName"><?=$shopName?></span>
    </div>
</div>

<?php for($i = 0;$i<count($commodities);$i++){?>
<div class="lineDiv"></div>

<div class="shopContentDiv_<?= $i ?>">
        <div class="shopImgDiv">
            <img  class="shopImg" src="<?= $commodities[$i]['pic_url']?>"/>
        </div>
        <div class="shopTextDiv">
            <div style="height:25px;overflow: hidden"><span id="tvContent"><?= $commodities[$i]['commodity_name']?></span></div>

            <div style="margin-top: 6px">
                <div ><span id="tvShopPrice">￥<?= $commodities[$i]['price'] ?></span></div>
                <div style="font-size: 12px;color: #4A4A4A;">规格：
                <span >
                    <?php for ($j = 0; $j < count($attrsAll[$i]); $j++) { ?>
                        <?= $attrsAll[$i][$j]['attr_opt_name'] ?>
                    <?php } ?>
                </span>
                </div>
                <div style="font-size: 12px;color: #4A4A4A;">库存：
                    <span class = 'stock_num'>
                        <?= $commodities[$i]['stock_num'] ?>
                    </span>
                </div>
                <div style="clear: both"></div>
            </div>

            <div class="cpsx_info_num">
                <div class="deleteDiv" onclick="deletesSum(<?= $i?>)">-</div>
                <?php
                if(!$sums){?>
                <div id="sumId_<?= $i?>" class="shopSum" >1</div>
                <?php } else{?>
                <div id="sumId_<?= $i?>" class="shopSum" ><?= $sums[$i]?></div>
                <?php } ?>
                <div class="addDiv" onclick="addSum(<?= $i?>)">+</div>
            </div>
        </div>
    <div  style="clear: both"></div>
</div>

<div class="lineDiv"></div>

<?php }?>
<div>
    <div class="sendDiv">
        运费:
        <span id="tvKind">￥0.00</span>
    </div>
</div>

<div class="lineDiv"></div>

<div>
    <div class="sendDiv">
        <span id="tvSend">买家留言</span>
        <input type="text" placeholder="点击留言" name="message" id="message">
    </div>
</div>

<div class="lineDiv"></div>

<div>
    <div class="sendDiv">
        <span id="tvSend">合计</span>
        <div class="sumPriceDiv">￥
            <span id="tvsSumPrice">0.00</span></div>
    </div>
</div>

<div align="center" style="margin-top: 19px;margin-bottom: 10px" onclick="clickToPay()"><div  class="payDiv">去支付</div>

</div>
<!--<div align="center" style="margin-top: 19px;margin-bottom: 10px" onclick="test()"><div  class="payDiv">test</div>-->
<!---->
<!--</div>-->
<div id="hidediv" style="display:none">

</div>







<div class="modal fade" id="followModal">
    <div class="modal-dialog modal-lg" style="width:90%;margin-top: 50%;margin-left: 5%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" style="font-size: 18px;color: #777">你是否想关注若问科技</h4>
                <p style="display: none" id="banner_id_p"></p>
                <div class="modal-body">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" id="noRemind"><span style="color: #aaa;">不在提醒</span></button>
                        <button type="button" class="btn btn-default" id=follow><span style="color:rgb(4,190,2)">关注</span></button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
     </div>
</div>



<script type="text/javascript">
    totalSum();
    var params="";
    var orderform_id="";
    function addSum(position){
        var $sum = document.getElementById("sumId_" + position).innerText;
        $sum = (parseInt($sum) + 1).toString();

        document.getElementById("sumId_" + position).innerText = $sum;
        if(parseInt($sum)> parseInt($(".shopContentDiv_"+position).find('span.stock_num').text())){
            alert('非常抱歉,因库存不足,暂时无法支付');
            document.getElementById("sumId_" + position).innerText = ($sum-1).toString();
        }
        totalSum();
    }

    function deletesSum(position){
        var $sum = document.getElementById("sumId_" + position).innerText;

        if(parseInt($sum) > 1){
            $sum = (parseInt($sum) - 1).toString();
            document.getElementById("sumId_" + position).innerText = $sum;
            totalSum();
        }else{
            alert("最少数量为1")
        }
    }

    function changeText(){
        totalSum();
    }

    function totalSum(){
        var postage = parseFloat(0.00).toFixed(2);

        var total = parseFloat(0.00).toFixed(2);

        var commodity = (<?php echo json_encode($commodities)?>);
        var province = "<?=$address['province']?>";
        var postageTemplates = (<?=$postage_templates?>);
        for(var j= 0 ; j < commodity.length ;j++){
            var $sum = document.getElementById("sumId_" + j).innerText;
            if(!$sum){
                $sum = 0;
            }
            var unit_postage = parseFloat(0.00).toFixed(2);
            if(postageTemplates[commodity[j].commodity_id]) {
                if(postageTemplates[commodity[j].commodity_id].details[province]) {
                    unit_postage = parseFloat(postageTemplates[commodity[j].commodity_id].details[province]).toFixed(2);
                } else {
                    unit_postage = parseFloat(postageTemplates[commodity[j].commodity_id].default).toFixed(2);
                }
            }
            postage = parseFloat($sum) * parseFloat(unit_postage) + parseFloat(postage);
            total = parseFloat($sum) * parseFloat(commodity[j].price) + parseFloat(total);
        }
        total = total + postage;

        document.getElementById("tvKind").innerText = "￥" + parseFloat(postage).toFixed(2).toString();
        document.getElementById("tvsSumPrice").innerText  = parseFloat(total).toFixed(2).toString();

    }
    var commodity = (<?php echo json_encode($commodities)?>);
    var attr = (<?php echo json_encode($attrsAll)?>);

    function goToNewAddress(){
        var sums=[];
        var commodityIds = [];
        var attrIds = [];

        for (var i = 0; i < commodity.length; i++) {
            sums.push(document.getElementById("sumId_" + i).innerText);
            commodityIds.push(commodity[i].commodity_id);
            attrIds.push(getCommodityMsg(i));
        }

        var sums = JSON.stringify(sums);
        location.href = "choose-address?sums="+sums+"&commodity_ids="+JSON.stringify(commodityIds) +"&attr_opt_ids="
            +JSON.stringify(attrIds)+"&cart_ids="+JSON.stringify(<?= $cartIds ?>);
    }

    function getCommodityMsg(position){
        var attr_opts = attr[position];
        var attr_opt_ids = new Array();
        for (var i=0;i<attr_opts.length;i++){
            attr_opt_ids.push(attr_opts[i].attr_opt_id);   //获取商品规格的attr_opt_id
        }
        return attr_opt_ids;
    }

    function jsApiCall(payparam)
    {
        var noRemind=<?php echo $no_remind?>;
        console.log(payparam);
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
           payparam,
            function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok"){
                    $.ajax({
                        type:"POST",
                        dataType:"json",
                        data: {
                            "orderform_id": orderform_id

                        },
                        url: "getorderstatus",
                        success: function (json) {
                            if(json.code){
                                console.log('success');
                                location.href="my-order?status=1";
                                alert('如果未关注,可点击左上角关注按钮');
//                                $.ajax({
//                                    data:{
//
//                                    },
//                                    url:"is-follow",
//                                    success:function(json){
//                                        if(json['subscribe']==0 && noRemind==0){
//                                            $("#followModal").modal();
//                                        }
//                                        else {
//                                            location.href="my-order?status=1";
//                                        }
//                                    },
//                                    error:function(data){
//                                        console.log(data);
//                                    }
//
//
//                                })

                            }

                        },
                        error: function (XmlHttpRequest,textStatus, errorThrown) {
                            console.log(XmlHttpRequest.responseText);
                            console.log(textStatus);

                            //  location.href = "login";
                        }
                    });

                }else if(res.err_msg == "get_brand_wcpay_request:cancel")
                {

                    alert('支付过程中用户取消！');
                    window.location.reload();
                    return;

                }else{

                    alert('支付失败！');
                    return;
                }
                //WeixinJSBridge.log(res.err_msg);
              //  console.log(res.err_code+res.err_desc+res.err_msg);
            }
        );
    }

    function callpay(pay_param)
    {
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', jsApiCall.bind(this,pay_param), false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', jsApiCall.bind(this,pay_param));
                document.attachEvent('onWeixinJSBridgeReady', jsApiCall.bind(this,pay_param));
            }
        }else{
            jsApiCall(pay_param);
        }
    }
    function clickToPay(){
        var commodity_ids = getCommodityId();
        var commodity_sums = getCommoditySum();
        var total = document.getElementById("tvsSumPrice").innerText;
        var postage = document.getElementById("tvKind").innerText.substring(1);
        var remarks = $('#message').val();

        var address_Id = "<?=Html::encode($addressId)?>";

        if(!address_Id){
            alert('请先添加地址');
            return;
        }

        var len = (<?= count($commodities)?>);
        for(var i=0;i<len;i++){
            var $sum = document.getElementById("sumId_" + i).innerText;

            if(parseInt($sum)> parseInt($(".shopContentDiv_"+i).find('span.stock_num').text())){
                alert('非常抱歉,因库存不足,暂时无法支付');
                window.location.reload();
                return;
            }
        }

        var cart_ids = JSON.stringify(<?php echo $cartIds?>);
        var attr_ids = JSON.stringify(<?php echo $attrIds?>);
        $.ajax({
            type:"POST",
            dataType:"json",
            data: {
                "commodity_ids": JSON.stringify(commodity_ids),
                "commodity_sums":JSON.stringify(commodity_sums),
                "totalMoney":total,
                "postage":postage,
                "cart_ids":cart_ids,
                "remarks":remarks,
                "attr_ids":attr_ids,
                "address_Id":address_Id,
                "share_id":<?php echo  $share_id?$share_id:-1?>
            },
            url: "create-order",
            success: function (json) {
                    console.log('json->',json);
                    params=json.js;
                    console.log('params->',params);
                    orderform_id=json.orderform_id;
                    callpay(params);

            },
            error: function (XmlHttpRequest,textStatus, errorThrown) {
                alert("生成订单失败");
                console.log(XmlHttpRequest.responseText);
                console.log(textStatus);

              //  location.href = "login";
            }
        });
    }








    function getCommodityId(){
        var commodity = (<?php echo json_encode($commodities)?>);
        var ids = new Array();
        for (var i=0;i<commodity.length;i++){
            ids.push(parseInt(commodity[i].commodity_id));   //获取商品id
        }
        return ids;
    }

    function getCommoditySum(){
        var commodity = (<?php echo json_encode($commodities)?>);
        var sums = new Array();
        for (var i=0;i<commodity.length;i++){
            var $sum = document.getElementById("sumId_" + i).innerText;
            sums.push(parseInt($sum));
        }
        return sums;
    }


    $("#follow").click(function(){
        location.href='http://mp.weixin.qq.com/s?__biz=MzA5MDIwNTE0Mw==&mid=2649399234&idx=1&sn=0b77d456802c426493639d1e4a30acba&scene=0#wechat_redirect';
    })
    $("#noRemind").click(function(){
        var user_id=JSON.stringify(<?php echo $user_id?>);
        $.ajax({
            type:"POST",
            dataType:"json",
            data:{
                "user_id":user_id
            },
            url:'no-remind',
            success:function(){

            },
            error:function(){

            }


        })
    })


</script>